/**
 * Created by Administrator on 2018/12/29.
 */
$(function () {
    clearTheForm();// 清空表单
    addNewMould();// 保存模具信息
    refreshThMouldNo();// 刷新模具编号
    choosePic();//选择图片
    $('input.easyui-textbox').textbox({
        validateOnCreate: false, // 创建时不验证，底色为白色
        err: function(target, message, action){
            var opts = $(target).validatebox('options');
            message = message || opts.prompt;
            $.fn.validatebox.defaults.err(target, message, action);
        }
    });
    jQuery(".uploadify").uploadify(uploadifyConfig);
});
// 保存模具信息
var addNewMould = function () {
    $("#save").click(function () {
        if($("input[name='mouldNo']").val()=="") {
            showDialogWithContent("请输入模具编号！");
            return;
        } else if($("input[name='mouldColor']").val()==""){
            showDialogWithContent("请输入模具颜色！");
            return;
        } else if($("input[name='mouldName']").val()==""){
            showDialogWithContent("请输入模具名称！");
            return;
        } else if($("input[name='spec']").val()==""){
            showDialogWithContent("请输入模具规格！");
            return;
        }
        var params = new Object();
        params.mouldNo = $("input[name='mouldNo']").val();
        params.mouldColor = $("input[name='mouldColor']").val();
        params.mouldName = $("input[name='mouldName']").val();
        params.spec = $("input[name='spec']").val();
        params.modelNo = $("input[name='modelNo']").val();
        params.material = $("input[name='material']").val();
        params.mouldClz = $("input[name='mouldClz']").val();
        params.remark = $("input[name='remark']").val();

        var fileIds = "";
        $("input[name='file_ids']").each(function (index, element) {
            fileIds += "," + $(this).val();
        });
        if("" != fileIds) {
            fileIds = fileIds.substring(1, fileIds.length);
        }
        params.picAddr = fileIds;
        var jsonstr = postSyncAjax("/addNewMould", params);
        if(jsonstr.success) {
            //$("#viewPicDiv").hide();
            //$("#pic").val("");
            //$("#viewPic").prop("src","");
            //$("#picAddr").val("");
            showDialogWithContent("添加成功！");
        } else {
            if (jsonstr.status == 401) {
                showDialogSetTime(jsonstr.msg, function () {
                    window.top.location.href = "/index";
                }, 5000);
            }
            //$("#viewPicDiv").hide();
            //$("#viewPic").prop("src","");
            //$("#picAddr").val("");
            showDialogWithContent("添加失败：" + jsonstr.msg);
            return;
        }
        /*// 用于ajax上传文件和普通数据
         var formData = new FormData(document.getElementById("addMouldForm"));
         console.log(formData);
         var jsonstr = postIncludeFileSyncAjax("/addNewMould",formData);
         console.log(jsonstr);
         if(jsonstr.status == 300) {
         showDialogWithContent("添加成功！");
         } else {
         if(jsonstr.status == 401){
         showDialogSetTime(jsonstr.msg,function () {
         window.top.location.href = "/index";
         },5000);
         }
         showDialogWithContent("添加失败："+jsonstr.msg);
         return;
         }*/
    });
}
// 刷新模具编号
var refreshThMouldNo = function () {
    $("#refresh").click(function () {
        var date = new Date();
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var day = date.getDate();
        var hour = date.getHours();
        var minute = date.getMinutes();
        var seconds= date.getSeconds();
        month = month < 10 ? '0' + month : month;
        day = day < 10 ? '0' + day : day;
        hour = hour < 10 ? '0' + hour : hour;
        minute = minute < 10 ? '0' + minute : minute;
        seconds = seconds < 10 ? '0' + seconds : seconds;
        $("#mouldNo").textbox("setValue","M" + year + "" + month + "" + day + "" + hour + "" + minute + "" + seconds);
        $("#fileItem").html("");
    });
}
// 清空表单
var clearTheForm = function () {
    $("#clear").click(function () {
        $('#addMouldForm').form('clear');
    });
    $("#viewPicDiv").hide();
    $("#viewPic").prop("src","");
    $("#picAddr").val("");
}
// 选择图片
var choosePic = function () {
    var picId = $('input[name=\'pic\']').prop("id");
    $(document).off('change','input[name=\'pic\']').on('change','input[name=\'pic\']',function () {
        console.log("aaa");
        if($(this).val()!=null && $(this).val()!=""){
            console.log($(this).val());
            var params = new Object();
            params.picAddr = $("#picAddr").val();
            $.ajaxFileUpload({
                url: "/uploadTempMouldPic",   //用于文件上传的服务器端请求地址
                secureuri: false,      //是否需要安全协议，一般设置为false
                fileElementId: [picId], //文件上传域的ID
                dataType: 'json',           //返回值类型 一般设置为json
                data:params,
                type:'post',
                success: function (data, status)  //服务器成功响应处理函数
                {
                    console.log(data);
                    console.info(status);
                    if(data.success == true) {
                        $("#viewPicDiv").show();
                        $("#viewPic").prop("src",data.data);
                        $("#picAddr").val(data.data);
                        console.log($("#picAddr").val());
                    } else {
                        if(data.status == 401){
                            showDialogSetTime(data.msg,function () {
                                window.top.location.href = "/index";
                            },5000);
                        }
                        $("#viewPicDiv").hide();
                        $("#viewPic").prop("src","");
                        $("#picAddr").val();
                        return;
                    }
                },
                error: function (data, status, e)//服务器响应失败处理函数
                {
                    $("#viewPicDiv").hide();
                    $("#viewPic").attr("src","");
                    $("#picAddr").val();
                    showDialogWithContent("上传过程出错，错误信息："+e);
                }
            });
        } else {
            $("#viewPicDiv").hide();
            $("#viewPic").attr("src","");
            $("#picAddr").val();
        }
    });
}

var uploadifyConfig = {
    'uploader'       : '/sh/uploadify/uploadify.swf?r=' + Math.random(),
    'script'         : '/file/upload?r=' + Math.random(),
    'scriptData'     : {},
    'buttonImg'	     : '/sh/uploadify/theme/default/fill-090.png',
    'cancelImg'      : '/sh/uploadify/cancel.png',
    'height'         : '16',
    'width'          : '16',
    'auto'           : true,
    'multi'          : true,
    'sizeLimit'      : 100000000, //100M
    'fileDataName'   :'file',
    'fileDesc'       : '支持格式：jpg,jpeg,png',
    'fileExt'        : '*.jpg;*.jpeg;*.png',
    onComplete:function(event, ID, fileObj, response, data){
        var json = jQuery.parseJSON(response);
        console.log(fileObj);
        if(json.success) {
            var mydata = json.data;
            mydata = mydata.replace("[","").replace("]","");
            mydata = jQuery.parseJSON(mydata);
            console.log(mydata);
            var file_id = mydata.file_id;
            var file_path = mydata.file_path;
            //var obj = jQuery("#"+jQuery(event.target).attr('id'));
            var obj = $("#fileItem");
            var queue = jQuery("#"+jQuery(event.target).attr('id')+"Queue");
            //console.log(event.target);
            //console.log(jQuery(event.target).attr('id'));
            var html = "<div class='file-container' id='file_"+file_id+"'>";
            html += "<input type='hidden' name='file_ids' value='"+file_id+"'/>";
            if(file_path.endWith(".txt")){
                html += "<img src='/sh/image/txt.png'/>";
            }else if(file_path.endWith(".png")||file_path.endWith(".jpg")||file_path.endWith(".jpeg")){
                html += "<img src='/sh/image/img.png'/>";
            }else if(file_path.endWith(".rar")||file_path.endWith(".zip")){
                html += "<img src='/sh/image/rar.png'/>";
            }else if(file_path.endWith(".pdf")){
                html += "<img src='/sh/image/pdf.png'/>";
            }else if(file_path.endWith(".xls")||file_path.endWith(".xlsx")){
                html += "<img src='/sh/image/xls.png'/>";
            }else{
                html += "<img src='/sh/image/blue-document-word-text.png'/>";
            }
            html += "<a href=\"javascript:downloadFile('"+file_id+"')\">"+fileObj.name+"</a>";
            html += "<div class=\"file-row\">"
            //html += "<button type=\"button\" onclick=\"delFile('" + json.unid + "');\" class=\"btn btn-default btn-sm\" id='file_" + json.unid + "' style=\"margin-left:10px;float:none;\">删&nbsp;除</button>&nbsp;";
            html += "<span class='file-delete' onclick=\"javascript:delFile('" + file_id + "');\" id='file_"+file_id+"' >&nbsp;</span>";
            html += "<img src='"+file_path+"' width='50px' height='50px'/>";
            html += "</div>";
            html += "</div>";
            var targetObj = $("#fileItem").append(html);
            //console.log(obj.parent().html());
            $.parser.parse(targetObj);
        } else {
            showDialogWithContent(json.msg);
        }
    },
    onError:function(event,ID,fileObj,errorObj) {
        if(errorObj.type=='File Size'){
            showDialogWithContent("文件大小超过限制(500M)");
        }
    }
};

function downloadFile(file_id) {
    /*var params = new Object();
    params.fileId = file_id;
    var jsonstr = postSyncAjax("/file/download", params);
    if(!jsonstr.success) {
        if (jsonstr.status == 401) {
            showDialogSetTime(jsonstr.msg, function () {
                window.top.location.href = "/index";
            }, 5000);
        }
        showDialogWithContent("下载失败：" + jsonstr.msg);
        return;
    }*/
    window.top.location.href = "/file/download/"+file_id;
}

function delFile(file_id) {
    $.messager.confirm("确认对话框","确定要删除该图片，删除后不可恢复？",function (r) {
        if (r) {
            var params = new Object();
            params.fileId = file_id;
            var jsonstr = postSyncAjax("/file/delete", params);
            if (jsonstr.success) {
                $("#file_" + file_id).hide();
            } else {
                if (jsonstr.status == 401) {
                    showDialogSetTime(jsonstr.msg, function () {
                        window.top.location.href = "/index";
                    }, 5000);
                }
                showDialogWithContent("删除失败：" + jsonstr.msg);
                return;
            }
        }
    });
}